/*
 * 
 */
package com.c2soft.nepalcmx.webapp.security;

import java.io.IOException;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;

public class RoleBasedAuthenticationSuccessRedirectHandler extends
		SimpleUrlAuthenticationSuccessHandler {
	
	
	@Override
	public void onAuthenticationSuccess(HttpServletRequest request,
			HttpServletResponse response, Authentication authentication)
			throws ServletException, IOException {
	
		  request.getSession().setAttribute("UsrId", request.getParameter("userId"));
			
		String userTargetUrl = "/clientpage";
		String brokerTargetUrl = "/home";
		String exchangeTargetUrl = "/exchangehome";
			
		
		Set<String> roles = AuthorityUtils.authorityListToSet(authentication
				.getAuthorities());
		
		if (roles.contains("ROLE_BROKER")) {
			
			getRedirectStrategy().sendRedirect(request, response,
					brokerTargetUrl);
		} else if (roles.contains("ROLE_USER")) {
			
			getRedirectStrategy()
					.sendRedirect(request, response, userTargetUrl);
		}else if (roles.contains("ROLE_EXCHANGE")) {
		
			getRedirectStrategy()
			.sendRedirect(request, response, exchangeTargetUrl);
		}
		else {
			super.onAuthenticationSuccess(request, response, authentication);
			return;
		}
	}
}
